<template>
  <div class="counter">
    <h2>Counter: {{ count }}</h2>
    <button @click="startPolling" :disabled="isPolling">开始轮询</button>
    <button @click="stopPolling" :disabled="!isPolling">结束轮询</button>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'

const count = ref(0)
const isPolling = ref(false)
let pollingInterval = null

const fetchCount = async () => {
  try {
    const response = await fetch('http://localhost:3000/polling')
    const data = await response.json()
    count.value = data.count
  } catch (error) {
    console.error('Failed to fetch counter:', error)
  }
}

const startPolling = () => {
  isPolling.value = true
  fetchCount() // Fetch immediately
  pollingInterval = setInterval(fetchCount, 500) // Poll every 500ms
}

const stopPolling = () => {
  isPolling.value = false
  if (pollingInterval) {
    clearInterval(pollingInterval)
    pollingInterval = null
  }
}

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
.counter {
  text-align: center;
  margin: 20px;
}

button {
  margin: 0 10px;
  padding: 8px 16px;
  font-size: 16px;
  cursor: pointer;
}

button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
</style> 